package com.qzdsoft.erpcloud.controller;

import java.awt.image.BufferedImage;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.qzdsoft.erpcloud.controller.common.SessionUtil;
import com.qzdsoft.erpcloud.service.sys.RedisService;
import com.qzdsoft.utils.SysUtils;

/**
 * Created by Admin
 */
@Controller
@RequestMapping("/")
public class KaptchaController {

    @Autowired
    private DefaultKaptcha defaultKaptcha;

    @Autowired
    private RedisService redisService;

    /**
     * 获取验证码图片
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/kaptch")
    public ModelAndView getKaptchaImage(HttpServletRequest request, HttpServletResponse response) throws Exception {
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");

        String text = defaultKaptcha.createText();               // 验证码内容
        redisService.set(SysUtils.redisKaptcha(SessionUtil.getSessionId(request)), text, 60);
        BufferedImage bi = defaultKaptcha.createImage(text);
        ServletOutputStream out = response.getOutputStream();

        try {
            ImageIO.write(bi, "jpg", out);
            out.flush();
        } finally {
            out.close();
        }
        return null;
    }
}
